package datamodels

import (
	"micro-oauth/datamodels/enum"
	"net/url"
	"strings"
)

type Client struct {
	MyGormModel
	PartnerId           uint64          `json:"partner_id,string" gorm:"index"`
	ScopeId             uint64          `json:"scope_id,string;default:0"`
	Name                string          `json:"name" gorm:"size:100"`
	ClientId            string          `json:"client_id" gorm:"size:255;unique_index"`
	Secret              string          `json:"secret" gorm:"size:255"`
	RedirectURIs        string          `json:"redirect_uris" gorm:"size:255"`
	Type                enum.ClientType `json:"type" gorm:"size:50;default:'WEB'"`
	TokenExpireDuration int64           `json:"token_expire_duration"`
	ScopeCodes          string          `json:"scope_codes" gorm:"size:255"`
	TerminalId          uint64          `json:"terminal_id,string"`
}

func (c *Client) ContainScope(scope string) bool {
	codes := strings.Split(c.ScopeCodes, " ")
	for _, code := range codes {
		if code == scope {
			return true
		}
	}
	return false
}

func (c *Client) ValidRedirectURI(uri string) bool {
	urlObj, err := url.Parse(uri)
	if err != nil {
		return false
	}
	urls := strings.Split(c.RedirectURIs, " ")
	for _, urlStr := range urls {
		urlObj2, err := url.Parse(urlStr)
		if err != nil {
			continue
		}
		if (urlObj.Hostname() == urlObj2.Hostname()) && (urlObj.Path == urlObj2.Path) {
			return true
		}
	}
	return false
}

type CreatePosClientRequest struct {
	PartnerId  uint64
	TerminalId uint64
	ScopeId    uint64
}
